package com.xm9m.web.service.security;

import com.salesmanager.core.business.customer.model.Customer;
import com.salesmanager.core.business.customer.model.CustomerAuths;
import com.salesmanager.core.business.customer.model.CustomerCriteria;
import com.salesmanager.core.business.customer.service.CustomerService;
import com.salesmanager.core.business.user.model.Group;
import com.salesmanager.core.business.user.model.Permission;
import com.salesmanager.core.business.user.service.GroupService;
import com.salesmanager.core.business.user.service.PermissionService;
import com.salesmanager.core.utils.EncryptionUtil;
import com.salesmanager.web.constants.Constants;
import com.xm9m.web.service.entity.security.SecurityCustomer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;


public class UserServicesImpl implements WebUserServices {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UserServicesImpl.class);

	@Autowired
	private CustomerService customerService;

	@Autowired
	protected PermissionService  permissionService;
	
	@Autowired
	protected GroupService   groupService;

	@Override
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		Customer user = null;
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        String loginName = null;
        String password = null;

		try {
			LOGGER.debug("验证用户{}",userName);

            //deviceId登陆
            if (userName.contains("deviceId:")){
                loginName = userName.replace("deviceId:", "");
                password = EncryptionUtil.encode(EncryptionUtil.SHA1, loginName);
                CustomerAuths customerAuths = customerService.getCustomerAuthByDeviceId(loginName);
                if(customerAuths.getCustomer() == null) return null;
                user = customerService.getById(customerAuths.getCustomer().getId());

            } else {
                loginName = userName;
                user = customerService.getByTelphone(userName);

                if(user == null) return null;

                //密码凭证
                Set<CustomerAuths> auths =  user.getAuths();
                for (CustomerAuths customerAuths : auths){
                    if (customerAuths.getIdentityType() == 1){ //手机号
                        password = customerAuths.getCertificate();
                        break;
                    }
                }
            }



			GrantedAuthority role =new SimpleGrantedAuthority(Constants.PERMISSION_CUSTOMER_AUTHENTICATED);
			authorities.add(role);
	
			List<Integer> groupsId = new ArrayList<Integer>();
			List<Group> groups = user.getGroups();
			for(Group group : groups) {
				groupsId.add(group.getId());
			}

	    	List<Permission> permissions = permissionService.getPermissions(groupsId);
	    	for(Permission permission : permissions) {
	    		GrantedAuthority auth = new SimpleGrantedAuthority(permission.getPermissionName());
	    		authorities.add(auth);
	    	}
    	
		} catch (Exception e) {
			LOGGER.error("Exception while querrying user",e);
		}


		SecurityCustomer secUser = new SecurityCustomer(loginName, password, authorities);
		secUser.setCustomerId(user.getId());
		secUser.setNick(user.getNick());
		secUser.setTelphone(user.getTelphone());
		return secUser;
	}




}
